package dongshi.daddy.dongsrmutitidatasoucespringbootstarter.datasource;

import com.zaxxer.hikari.HikariDataSource;
import dongshi.daddy.dongsrmutitidatasoucespringbootstarter.holder.MyCurrenetDatasourceHolder;
import dongshi.daddy.dongsrmutitidatasoucespringbootstarter.model.MyDbConnectionInfo;
import dongshi.daddy.dongsrmutitidatasoucespringbootstarter.properties.CustomDatasourceProperties;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

public class MyCustomDatasource extends HikariDataSource {

    @Resource
    private CustomDatasourceProperties customDatasourceProperties;

    @Override
    public Connection getConnection() throws SQLException {
        // 获取当前的routekey
        String routeKey = MyCurrenetDatasourceHolder.queryCurrentDataSourceConfig();
        // 根据routkey从配置文件类中获取数据库链接信息
        Map<String, Object> datasouresMap = customDatasourceProperties
                .getDatasoures()
                .get(routeKey);
        if (datasouresMap == null) {
            throw new IllegalArgumentException(
                    "routeKey: " + routeKey + " 是不是一个合法的key，根据您提供的配置文件，合法的key有:"
                            + customDatasourceProperties.getDatasoures().keySet()
            );
        }
        MyDbConnectionInfo myDbConnectionInfo = new MyDbConnectionInfo();
        myDbConnectionInfo.setHost(datasouresMap.get("host").toString());
        myDbConnectionInfo.setPort(datasouresMap.get("port").toString());
        String username = datasouresMap.get("username").toString();
        myDbConnectionInfo.setUsername(username);
        String password = datasouresMap.get("password").toString();
        myDbConnectionInfo.setPassword(password);
        myDbConnectionInfo.setDatabase(datasouresMap.get("database").toString());
        String jdbcUrl = myDbConnectionInfo.buildJdbcUrl();

        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setJdbcUrl(jdbcUrl);
        hikariDataSource.setUsername(username);
        hikariDataSource.setPassword(password);
        hikariDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        return hikariDataSource.getConnection();
    }
}
